package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.entity.ProductSalesOrderProgress;
import org.jeecg.modules.oms.mapper.ProductSalesOrderProgressMapper;
import org.jeecg.modules.oms.service.IProductSalesOrderProgressService;
import org.jeecg.modules.oms.service.IProductSalesOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 成品销售订单进度服务实现类
 */
@Slf4j
@Service
public class ProductSalesOrderProgressServiceImpl extends ServiceImpl<ProductSalesOrderProgressMapper, ProductSalesOrderProgress> implements IProductSalesOrderProgressService {

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IProductSalesOrderService productSalesOrderService;
    
    @Override
    public List<ProductSalesOrderProgress> getProgressListByOrderId(String orderId) {
        return baseMapper.getProgressListByOrderId(orderId);
    }

    @Override
    public IPage<ProductSalesOrderProgress> getProgressPageList(Page<ProductSalesOrderProgress> page, ProductSalesOrderProgress progress) {
        return baseMapper.getProgressPageList(page, progress);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProgressByOrderId(String orderId) {
        return baseMapper.deleteProgressByOrderId(orderId) >= 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProgress(ProductSalesOrderProgress progress) {
        // 设置状态变更时间
        if (progress.getChangeTime() == null) {
            progress.setChangeTime(new Date());
        }
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null && progress.getOperatorId() == null) {
            progress.setOperatorId(loginUser.getId());
            progress.setOperatorName(loginUser.getRealname());
        }
        
        boolean result = save(progress);
        if (!result) {
            return false;
        }
        
        // 更新订单状态
        updateOrderStatus(progress.getOrderId(), progress.getNewStatus());
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editProgress(ProductSalesOrderProgress progress) {
        // 查询原进度记录
        ProductSalesOrderProgress oldProgress = getById(progress.getId());
        if (oldProgress == null) {
            return false;
        }
        
        // 设置状态变更时间（如果未提供）
        if (progress.getChangeTime() == null) {
            progress.setChangeTime(new Date());
        }
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null) {
            // 更新操作人信息（如果未提供）
            if (progress.getOperatorId() == null) {
                progress.setOperatorId(loginUser.getId());
                progress.setOperatorName(loginUser.getRealname());
            }
            
            // 设置更新人信息
            progress.setUpdateBy(loginUser.getUsername());
            progress.setUpdateTime(new Date());
        }
        
        // 保留原始创建人和创建时间
        progress.setCreateBy(oldProgress.getCreateBy());
        progress.setCreateTime(oldProgress.getCreateTime());
        
        // 更新进度记录
        boolean result = updateById(progress);
        if (!result) {
            return false;
        }
        
        // 如果状态发生变化，更新订单状态
        if (progress.getNewStatus() != null && !progress.getNewStatus().equals(oldProgress.getNewStatus())) {
            updateOrderStatus(progress.getOrderId(), progress.getNewStatus());
        }
        
        return true;
    }
    
    /**
     * 更新订单状态
     * 
     * @param orderId 订单ID
     * @param status 状态
     */
    private void updateOrderStatus(String orderId, Integer status) {
        try {
            // 获取订单信息
            ProductSalesOrder order = productSalesOrderService.getById(orderId);
            if (order == null) {
                return;
            }
            
            // 更新订单状态
            order.setStatus(status);
            productSalesOrderService.updateById(order);
        } catch (Exception e) {
            log.error("更新订单状态异常", e);
        }
    }
    
    @Override
    public IPage<ProductSalesOrderProgress> getProgressPageByOrderId(Page<ProductSalesOrderProgress> page, String orderId) {
        return baseMapper.getProgressPageByOrderId(page, orderId);
    }
} 